<?
session_start();
require_once 'functions.php';
require_once 'connect.php';
require_once 'PHPMailer/class.phpmailer.php';
$baseUrl = getBaseUrl();

$output = json_encode(array("status"=>"error", "message"=>"nok"));

if(isset($_POST['val']) && isset($_SESSION['userId']) && isset($_POST['specId'])){

	$sid = mysql_real_escape_string($_POST['specId']);
	$val = mysql_real_escape_string($_POST['val']);
	$uId = $_SESSION['userId'];
	


	$abfrage = "INSERT INTO ffxivc_ratings (
						specId
						,userId
						,value
						,cdate
						,udate
						 )
					VALUES (
						\"".$sid."\"
						,\"".$uId."\"
						,\"".$val."\"
						,\"".date('Y-m-d H:i:s')."\"
						,\"".date('Y-m-d H:i:s')."\"
						)
					ON DUPLICATE KEY
					UPDATE value = \"".$val."\"";

		$res = mysql_query($abfrage);
		
		if ($res){
			$output = json_encode(array("status"=>"success", "message"=>"ok"));
			$abfrage = "SELECT 
						user.email
						, user.notification 
						, user.userName
						FROM 
						((SELECT userId FROM ffxivc_specs WHERE specId = \"".$sid."\") specs   
						LEFT JOIN
						ffxivc_users user
						ON specs.userId = user.userId)";
			$res = mysql_query($abfrage);
			if ($res){
				$email = mysql_result($res, 0, "email");
				$userName = mysql_result($res, 0, "userName");
				$notification = mysql_result($res, 0, "notification");
				$sender = $_SESSION['userName'];
				if($notification == 'Y' && $userName != $sender){
					$mail = new PHPMailer(false);
					try {
						$mail->AddReplyTo('ffxivspecs@gmail.com', 'FFXIVSpecs');
						$mail->AddAddress($email, $userName);
						$mail->SetFrom('ffxivspecs@gmail.com', 'FFXIVSpecs');
						$mail->AddReplyTo('ffxivspecs@gmail.com', 'FFXIVSpecs');
						$mail->Subject = '[FFXIVSpecs] Notification';
						$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
						$mail->MsgHTML(file_get_contents($baseUrl."/php/send_email.php?action=RATE&comment=".urlencode($val)."&sender=".urlencode($sender)));
						$mail->Send();
					} catch (phpmailerException $e) {
					  echo $e->errorMessage(); //Pretty error messages from PHPMailer
					} catch (Exception $e) {
					  echo $e->getMessage(); //Boring error messages from anything else!
					}
				}
			}
			
		}else{
			$output = json_encode(array("status"=>"error", "message"=>mysql_error()));
		}

}
echo $output;

?>